package com.may.wind.service;

import com.may.wind.dao.RolePermissionRepository;
import com.may.wind.entity.Permission;
import com.may.wind.entity.RolePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class RolePermissionService {
    @Autowired
    RolePermissionRepository rolePermissionRepository;

    List<RolePermission> findAllByRoleId(long roleId) {
        return rolePermissionRepository.findAllByRoleId(roleId);
    }

    // @Modifying
    @Transactional
    public void savePermissionsChanges(long roleId, Collection<Permission> permissions) {
        rolePermissionRepository.deleteAllByRoleId(roleId);
        List<RolePermission> rolePermissions = new ArrayList<>();
        permissions.forEach(permission -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permission.getId());
            rolePermissions.add(rolePermission);
        });
        rolePermissionRepository.saveAll(rolePermissions);
    }
}
